// pm.cpp : Defines the exported functions for the DLL application.
//

#include <windows.h>

#include "jawt.h"
#include "jawt_md.h"
#include "pm.h"

#define MY_ASSERT(X,S) if (!X) { fprintf(stderr,"%s\n",S); return 0L;}

#define SYSTEM_WIN32   1
#define SYSTEM_WIN16   2
#define SYSTEM_JAVA    3
#define SYSTEM_OS2     4
#define SYSTEM_MAC     5
#define SYSTEM_XWINDOW 6

// property name to register own window procedure on hwnd
#define OLD_PROC_KEY (LPCWSTR)("oldwindowproc")
// signature of this window procedure
static LRESULT APIENTRY NativeViewWndProc( HWND , UINT , WPARAM , LPARAM ); 

/*
 * Class:     pm_devices_Devices
 * Method:    getLogicalDrives
 * Signature: ()[Ljava/lang/String;
 */
JNIEXPORT jobjectArray JNICALL Java_pm_devices_drives_DrivesUtil_getLogicalDrives
  (JNIEnv *env, jclass obj){
 DWORD dStrLength;
 char szDrives[256];
 jobjectArray strArray = NULL;

 memset(szDrives,'\0',sizeof(szDrives));
 dStrLength = GetLogicalDriveStrings(sizeof(szDrives),(LPTSTR)szDrives);

 /*
 ** The length of the array is returned from the above function minus the
 ** terminating null character. The function will place the names of the
 ** logical drives in the passed character array and null separate the names.
 ** The names will be in the form of X:\ where X denotes the drive letter.
 ** Therefore the length returned can be divided by 4 (the total number of
 ** characters in each name plus the null separator) to determine the number 
 ** of drives returned from the function. This number is then used to allocate
 ** storage for the array of Strings that will passed back to the caller of this
 ** function.
 */
 if (dStrLength)
 {
  int i, nDriveCount, nOffset = 0;

  nDriveCount = dStrLength/4;

  /* Allocate storage for Java array of String objects */
  strArray = env->NewObjectArray(nDriveCount,env->FindClass("java/lang/String"),env->NewStringUTF(""));

  /* Cycle through the string to get the names of the logical drives */
  for (i = 0; i < nDriveCount; i++)
  {
   /* Add the logical drive name as a Java String to the Java object array */
   env->SetObjectArrayElement(strArray, i, env->NewStringUTF(szDrives));

   /* Advance to the next logical drive name */
   szDrives[0] = szDrives[nOffset += 8];
  }
 }

 return strArray;
}


/*
 * Class:     pm_devices_Devices
 * Method:    getDriveType
 * Signature: (Ljava/lang/String;)I
 */
JNIEXPORT jint JNICALL Java_pm_devices_drives_DrivesUtil_getDriveType
  (JNIEnv *env, jclass obj, jstring jdrive)
{
 //const char *str = NULL;
 jint uReturn;
 jboolean iscopy;
 
 const jchar* drive = env->GetStringChars(jdrive, &iscopy);
 //str = env->GetStringUTFChars(drive, 0);
 uReturn = GetDriveType((LPCTSTR)drive);
 //uReturn = GetDriveType("c:\");
 env->ReleaseStringChars(jdrive, drive);

 return uReturn;
}

/*
 * Class:     pm_oo_NativeView
 * Method:    getNativeWindowSystemType
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_pm_oo_NativeOOViewComponent_getNativeWindowSystemType
  (JNIEnv *env, jobject obj)
{
	return (SYSTEM_WIN32);
}

/*
 * Class:     pm_oo_NativeView
 * Method:    getNativeWindow
 * Signature: ()J
 */
JNIEXPORT jlong JNICALL Java_pm_oo_NativeOOViewComponent_getNativeWindow
  (JNIEnv * env, jobject obj_this)
{
    jboolean                      result  ;
    jint                          lock    ;
    JAWT                          awt     ;
    JAWT_DrawingSurface*          ds      ;
    JAWT_DrawingSurfaceInfo*      dsi     ;
    JAWT_Win32DrawingSurfaceInfo* dsi_win ;
    HDC                           hdc     ;
    HWND                          hWnd    ;
    LONG                          hFuncPtr;

	/* Get the AWT */
	awt.version = JAWT_VERSION_1_3;
    result      = JAWT_GetAWT(env, &awt);
    MY_ASSERT(result!=JNI_FALSE,"wrong jawt version");

    /* Get the drawing surface */
	if ((ds = awt.GetDrawingSurface(env, obj_this)) == NULL)
		return 0L;

	/* Lock the drawing surface */
	lock = ds->Lock(ds);
    MY_ASSERT((lock & JAWT_LOCK_ERROR)==0,"can't lock the drawing surface");

	/* Get the drawing surface info */
	dsi = ds->GetDrawingSurfaceInfo(ds);

	/* Get the platform-specific drawing info */
	dsi_win = (JAWT_Win32DrawingSurfaceInfo*)dsi->platformInfo;
    hdc     = dsi_win->hdc;
    hWnd    = dsi_win->hwnd;

	/* Free the drawing surface info */
	ds->FreeDrawingSurfaceInfo(dsi);
	/* Unlock the drawing surface */
	ds->Unlock(ds);
	/* Free the drawing surface */
	awt.FreeDrawingSurface(ds);

    /* Register own window procedure
       Do it one times only! Otherwhise
       multiple instances will be registered
       and calls on such construct produce
       a stack overflow.
     */
    if (GetProp( hWnd, OLD_PROC_KEY )==0)
    {
        hFuncPtr = SetWindowLong( hWnd, GWL_WNDPROC, (DWORD)NativeViewWndProc );
        SetProp( hWnd, OLD_PROC_KEY, (HANDLE)hFuncPtr );
    }

    return ((jlong)hWnd);
}

/*****************************************************************************
 *
 * Class      : -
 * Method     : NativeViewWndProc
 * Signature  : -
 * Description: registered window handler to intercept window messages between
 *              java and office process
 */
static LRESULT APIENTRY NativeViewWndProc(
    HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    HANDLE hFuncPtr;
	//WNDPROC hFuncPtr;

    /* resize new created child window to fill out the java window complete */
    if (uMsg==WM_PARENTNOTIFY)
    {
        if (wParam == WM_CREATE)
        {
            RECT rect;
            HWND hChild = (HWND) lParam;

            GetClientRect(hWnd, &rect);

            SetWindowPos(hChild,
                        NULL,
                        rect.left,
                        rect.top,
                        rect.right - rect.left,
                        rect.bottom - rect.top,
                        SWP_NOZORDER);
        }
    }
    /* handle normal resize events */
    else if(uMsg==WM_SIZE)
    {
        WORD newHeight = HIWORD(lParam);
        WORD newWidth  = LOWORD(lParam);
        HWND hChild    = GetWindow(hWnd, GW_CHILD);

        if (hChild != NULL)
            SetWindowPos(hChild, NULL, 0, 0, newWidth, newHeight, SWP_NOZORDER);
    }

    /* forward request to original handler which is intercepted by this window procedure */
    hFuncPtr = GetProp(hWnd, OLD_PROC_KEY);
    MY_ASSERT(hFuncPtr,"lost original window proc handler");
    return CallWindowProc((WNDPROC)hFuncPtr, hWnd, uMsg, wParam, lParam);
} 